//
// Created by Bili_TianX_Computer on 2021/7/10.
//


#include "AdminUserManageDialog.h"

UserManageDialog::UserManageDialog()
{
    userTable = new QTableWidget();
    addButton = new QPushButton("添加用户");
    removeButton = new QPushButton("删除用户");
    buttonLayout = new QHBoxLayout();
    widgetLayout = new QVBoxLayout();

    buttonLayout->addWidget(addButton);
    buttonLayout->addWidget(removeButton);
    widgetLayout->addLayout(buttonLayout);
    widgetLayout->addWidget(userTable);

    setWindowTitle("添加用户");
    setLayout(widgetLayout);


    QStringList list;
    list << "姓名" << "用户名" << "密码" << "管理员";
    userTable->setColumnCount(list.size());
    userTable->setHorizontalHeaderLabels(list);
    for (const auto &user : *getUserList()) addUserToTable(user);
    removeButton->setDisabled(true);

    connect(addButton, SIGNAL(clicked()), this, SLOT(addButtonClicked()));
    connect(removeButton, SIGNAL(clicked()), this, SLOT(removeButtonClicked()));
    connect(userTable, SIGNAL(itemSelectionChanged()), this, SLOT(tableSelectRowSlot()));
}

void UserManageDialog::addUserToTable(const User &user)
{
    int r = userTable->rowCount();
    userTable->setRowCount(r + 1);
    userTable->setItem(r, 0, new QTableWidgetItem(user.name));
    userTable->setItem(r, 1, new QTableWidgetItem(user.account));
    userTable->setItem(r, 2, new QTableWidgetItem(user.password));
    auto *button = new QCheckBox();
    button->setChecked(user.isAdmin);
    userTable->setCellWidget(r, 3, button);
}

void UserManageDialog::addButtonClicked()
{
    auto *dialog = new AddUserDialog();
    if (dialog->exec() == Accepted)
    {
        getUserList()->append(*dialog->user);
        addUserToTable(*dialog->user);
    }
}

void UserManageDialog::removeButtonClicked()
{
    if (QMessageBox::question(this, "删除用户",
                              QString("是否删除用户“%1”?").arg(userTable->item(selectedRow, 0)->text()))
        == QMessageBox::Yes)
    {
        getUserList()->removeOne(getUserFromTable(selectedRow));
        userTable->removeRow(selectedRow);
    }

}

void UserManageDialog::tableSelectRowSlot()
{
    if (userTable->selectedRanges().size() == 1
        && userTable->selectedRanges()[0].rowCount() == 1
        && userTable->selectedRanges()[0].columnCount() == userTable->columnCount())
    {
        removeButton->setDisabled(false);
        selectedRow = userTable->selectedRanges()[0].topRow();
    } else
        removeButton->setDisabled(true);
}

User UserManageDialog::getUserFromTable(int row) const
{
    return User(
            userTable->item(row, 0)->text(),
            userTable->item(row, 1)->text(),
            userTable->item(row, 2)->text(),
            userTable->cellWidget(row, 3)->property("checked").toBool()
    );
}